<template>
  <div class="sample-info-query">
    <!-- 顶部标题和操作区 -->
    <div class="header">
      <h1>检测数据统计分析</h1>
      <div class="actions">
        <el-button type="primary" @click="exportData">
          <el-icon>
            <Download/>
          </el-icon>
          导出数据
        </el-button>
        <el-button @click="refreshData">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <div class="metrics-row">
      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon" style="background-color: #f0f7ff;">
            <el-icon color="#409EFF" :size="24">
              <Calendar/>
            </el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-title">今日检测量</div>
            <div class="metric-value">{{ metrics.todayTests }}</div>
            <div class="metric-change">
<span :class="metrics.todayChange >= 0 ? 'up' : 'down'">
{{ metrics.todayChange >= 0 ? '↑' : '↓' }}
{{ Math.abs(metrics.todayChange) }}%
</span>
              较昨日
            </div>
          </div>
        </div>
      </el-card>

      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon" style="background-color: #f0f9eb;">
            <el-icon color="#67C23A" :size="24">
              <Check/>
            </el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-title">合格率</div>
            <div class="metric-value">{{ metrics.passRate }}%</div>
            <div class="metric-change">
<span :class="metrics.passRateChange >= 0 ? 'up' : 'down'">
{{ metrics.passRateChange >= 0 ? '↑' : '↓' }}
{{ Math.abs(metrics.passRateChange) }}%
</span>
              较上周
            </div>
          </div>
        </div>
      </el-card>

      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon" style="background-color: #fef0f0;">
            <el-icon color="#F56C6C" :size="24">
              <Warning/>
            </el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-title">阳性检测数</div>
            <div class="metric-value">{{ metrics.abnormalCount }}</div>
            <div class="metric-change">
<span :class="metrics.abnormalChange >= 0 ? 'up' : 'down'">
{{ metrics.abnormalChange >= 0 ? '↑' : '↓' }}
{{ Math.abs(metrics.abnormalChange) }}%
</span>
              较上周
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表和数据表格区域 -->
    <div class="content-row">
      <!-- 趋势图表 -->
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="card-header">
            <span>检测趋势分析</span>
            <el-radio-group v-model="trendType" size="small" @change="updateTrendChart">
              <el-radio-button label="day">日趋势</el-radio-button>
              <el-radio-button label="week">周趋势</el-radio-button>
              <el-radio-button label="month">月趋势</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="trendChart" class="chart-container"></div>
      </el-card>

      <!-- 项目分布 -->
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="card-header">
            <span>项目检测分布</span>
          </div>
        </template>
        <div ref="projectChart" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 排行和数据表格 -->
    <div class="content-row">
      <!-- 检测项目排行 -->
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="card-header">
            <span>检测项目TOP10</span>
          </div>
        </template>
        <el-table :data="projectRanking" stripe style="width: 100%">
          <el-table-column prop="rank" label="排名" width="80" align="center">
            <template #default="{ $index }">
              <el-tag :type="getRankTagType($index + 1)">
                {{ $index + 1 }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="projectName" label="项目名称"/>
          <el-table-column prop="testCount" label="检测次数" width="120" align="center"/>
          <el-table-column prop="passRate" label="合格率" width="120" align="center">
            <template #default="{ row }">
              <el-progress
                  :percentage="row.passRate"
                  :color="row.passRate > 90 ? '#67C23A' : row.passRate > 70 ? '#E6A23C' : '#F56C6C'"
                  :show-text="false"
              />
              <span style="margin-left: 8px">{{ row.passRate }}%</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 详细数据表格 -->
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="card-header">
            <span>检测数据明细</span>
            <div class="table-actions">
              <el-input
                  v-model="tableSearch"
                  placeholder="搜索项目/样品"
                  clearable
                  style="width: 200px"
                  @clear="handleSearchClear"
              >
                <template #prefix>
                  <el-icon>
                    <Search/>
                  </el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </template>
        <el-table
            :data="filteredTableData"
            stripe
            style="width: 100%"
            v-loading="loading.table"
            @sort-change="handleSortChange"
        >
          <el-table-column prop="projectId" label="检测编号" width="120" sortable/>
          <el-table-column prop="projectName" label="项目名称" width="180" sortable/>
          <el-table-column prop="sampleName" label="样品名称" width="150"/>
          <el-table-column prop="testDate" label="检测日期" width="120" sortable/>
          <el-table-column prop="testPerson" label="检测人员" width="120"/>
          <el-table-column prop="testValue" label="检测值" width="120" align="right" sortable>
            <template #default="{ row }">
              {{ row.testValue }} <span class="unit">{{ row.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="检测结果" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getResultTagType(row.result)" size="small">
                {{ row.result }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="quality" label="合格性" width="120" align="center">
            <template #default="{ row }">
              <el-tag
                  :type="row.quality === '合格' ? 'success' : 'danger'"
                  size="small"
              >
                {{ row.quality || '--' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="showDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5,10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalItems"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情弹窗 -->
    <ResultDetailDialog
        v-model="detailDialogVisible"
        :detail-data="currentDetail"
    />
  </div>
</template>

<script setup>
import {ref, onMounted, computed, watch} from 'vue'
import {
  Download, Refresh, Calendar, Check,
  Warning, Timer, Search, Edit, Top, Bottom
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import ResultDetailDialog from "~/layout/components/ResultDetailDialog.vue";
import {getUserResults} from "~/api/results_man.js";
import {formatDate} from "~/utils/timeUtils.js";
import {ElMessage} from "element-plus";

// 关键指标数据
const metrics = ref({
  todayTests: 0,
  todayChange: 0,
  passRate: 0,
  passRateChange: 0,
  abnormalCount: 0,
  abnormalChange: 0
})

// 趋势图表类型
const trendType = ref('day')

// 项目排行数据
const projectRanking = ref([])

// 表格数据相关
const allTableData = ref([])
const tableSearch = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = computed(() => allTableData.value.length)
const loading = ref({table: false})

// 详情弹窗
const detailDialogVisible = ref(false)
const currentDetail = ref({})

// 图表引用
const trendChart = ref(null)
const projectChart = ref(null)
let trendChartInstance = null
let projectChartInstance = null

// 计算属性
const filteredTableData = computed(() => {
  let data = [...allTableData.value]

// 搜索过滤
  if (tableSearch.value) {
    const search = tableSearch.value.toLowerCase()
    data = data.filter(item =>
        item.projectName.toLowerCase().includes(search) ||
        item.sampleName.toLowerCase().includes(search)
    )
  }

// 分页
  const start = (currentPage.value - 1) * pageSize.value
  return data.slice(start, start + pageSize.value)
})

// 获取表格数据
const fetchTableData = async () => {
  try {
    loading.value.table = true;
    const resultsRes = await getUserResults();

    if (resultsRes.code === 10000) {
      allTableData.value = resultsRes.data.map(item => ({
        projectId: item.TestResultId,
        projectName: item.ProjectName,
        sampleName: item.SampleName,
        testDate: formatDate(item.TestDate),
        testPerson: item.TestPerson,
        testValue: item.TcValue,
        unit: item.Unit,
        result: item.TestResult,
        quality: item.Quality
      }));

// 更新统计数据
      updateMetrics(resultsRes.data);
      updateProjectRanking(resultsRes.data);
      updateTrendChart();
    }
  } catch (error) {
    console.error(' 获取检测结果列表数据失败', error);
    ElMessage.error(' 获取检测数据失败');
  } finally {
    loading.value.table = false;
  }
};

// 更新关键指标数据
const updateMetrics = (data) => {
// 获取今天和昨天的日期
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  const lastWeek = new Date(today);
  lastWeek.setDate(lastWeek.getDate() - 7);

// 格式化日期为YYYY-MM-DD
  const formatDateKey = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const todayKey = formatDateKey(today);
  const yesterdayKey = formatDateKey(yesterday);
  const lastWeekKey = formatDateKey(lastWeek);

// 统计数据
  const todayData = data.filter(item => {
    const itemDate = new Date(item.TestDate);
    return formatDateKey(itemDate) === todayKey;
  });

  const yesterdayData = data.filter(item => {
    const itemDate = new Date(item.TestDate);
    return formatDateKey(itemDate) === yesterdayKey;
  });

  const lastWeekData = data.filter(item => {
    const itemDate = new Date(item.TestDate);
    return formatDateKey(itemDate) === lastWeekKey;
  });

// 今日检测量
  const todayTests = todayData.length;
  const yesterdayTests = yesterdayData.length;
  const todayChange = yesterdayTests > 0 ?
      Math.round(((todayTests - yesterdayTests) / yesterdayTests) * 100) : todayTests > 0 ? 100 : 0;

// 合格率
  const todayPass = todayData.filter(item => item.Quality === '合格').length;
  const passRate = todayTests > 0 ? Math.round((todayPass / todayTests) * 100) : 0;

  const lastWeekPass = lastWeekData.filter(item => item.Quality === '合格').length;
  const lastWeekTotal = lastWeekData.length;
  const lastWeekRate = lastWeekTotal > 0 ? Math.round((lastWeekPass / lastWeekTotal) * 100) : 0;
  const passRateChange = lastWeekRate > 0 ? passRate - lastWeekRate : passRate > 0 ? 100 : 0;

// 阳性检测数
  const abnormalCount = todayData.filter(item => item.TestResult === '阳性').length;
  const lastWeekAbnormal = lastWeekData.filter(item => item.TestResult === '阳性').length;
  const abnormalChange = lastWeekAbnormal > 0 ?
      Math.round(((abnormalCount - lastWeekAbnormal) / lastWeekAbnormal) * 100) :
      abnormalCount > 0 ? 100 : 0;

// 更新指标
  metrics.value = {
    todayTests,
    todayChange,
    passRate,
    passRateChange,
    abnormalCount,
    abnormalChange
  };
};

// 更新项目排行
// 更新项目排行
const updateProjectRanking = (data) => {
// 按项目分组统计
  const projectStats = data.reduce((acc, item) => {
    if (!acc[item.ProjectName]) {
      acc[item.ProjectName] = {
        testCount: 0,
        passCount: 0
      };
    }
    acc[item.ProjectName].testCount++;
    if (item.Quality === '合格') {
      acc[item.ProjectName].passCount++;
    }
    return acc;
  }, {});

// 转换为数组并计算合格率
  projectRanking.value = Object.entries(projectStats)
      .map(([projectName, stats]) => ({
        projectName,
        testCount: stats.testCount,
        passRate: Math.round((stats.passCount / stats.testCount) * 100)
      }))
      .sort((a, b) => b.testCount - a.testCount) // 按检测次数排序
      .slice(0, 10); // 取前10

// 更新饼图数据
  updateProjectChart();
};

// 计算项目趋势（基于上周数据）
const calculateProjectTrend = (projectName, currentCount) => {
// 这里简化处理，实际应该比较上周同期的数据
// 随机生成一个趋势值用于演示
  return Math.round(Math.random() * 20 - 10);
};

// 更新趋势图表数据
const updateTrendChart = () => {
  if (!trendChartInstance || !allTableData.value.length) return;

  const data = allTableData.value;
  let chartData = {};

// 根据选择的趋势类型分组数据
  if (trendType.value === 'day') {
// 按天分组
    data.forEach(item => {
      const date = new Date(item.testDate);
      const dateKey = formatDateKey(date);
      if (!chartData[dateKey]) {
        chartData[dateKey] = {total: 0, pass: 0, abnormal: 0};
      }
      chartData[dateKey].total++;
      if (item.quality === '合格') chartData[dateKey].pass++;
      if (item.result === '阳性') chartData[dateKey].abnormal++;
    });
  } else if (trendType.value === 'week') {
// 按周分组
    data.forEach(item => {
      const date = new Date(item.testDate);
      const week = getWeekNumber(date);
      const weekKey = `${date.getFullYear()}-W${week}`;
      if (!chartData[weekKey]) {
        chartData[weekKey] = {total: 0, pass: 0, abnormal: 0};
      }
      chartData[weekKey].total++;
      if (item.quality === '合格') chartData[weekKey].pass++;
      if (item.result === '阳性') chartData[weekKey].abnormal++;
    });
  } else {
// 按月分组
    data.forEach(item => {
      const date = new Date(item.testDate);
      const monthKey = `${date.getFullYear()}-${date.getMonth() + 1}`;
      if (!chartData[monthKey]) {
        chartData[monthKey] = {total: 0, pass: 0, abnormal: 0};
      }
      chartData[monthKey].total++;
      if (item.quality === '合格') chartData[monthKey].pass++;
      if (item.result === '阳性') chartData[monthKey].abnormal++;
    });
  }

// 转换为图表需要的格式
  const dates = Object.keys(chartData).sort();
  const totalData = dates.map(date => chartData[date].total);
  const passData = dates.map(date => chartData[date].pass);
  const abnormalData = dates.map(date => chartData[date].abnormal);

  trendChartInstance.setOption({
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: trendType.value === 'day' ? 45 : 0,
        interval: 0
      }
    },
    series: [
      {data: totalData},
      {data: passData},
      {data: abnormalData}
    ]
  });
};

// 格式化日期为YYYY-MM-DD
const formatDateKey = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  // return `${year}-${month}-${day}`;
  return `${month}-${day}`;
};

// 获取周数
const getWeekNumber = (date) => {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7);
  const week1 = new Date(d.getFullYear(), 0, 4);
  return 1 + Math.round(((d.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
};

// 更新项目分布图表
const updateProjectChart = () => {
  if (!projectChartInstance || !projectRanking.value.length) return;

  projectChartInstance.setOption({
    series: [{
      data: projectRanking.value.map(item => ({
        value: item.testCount,
        name: item.projectName
      }))
    }]
  });
};

// 初始化图表
const initCharts = () => {
// 销毁已有实例
  if (trendChartInstance) {
    trendChartInstance.dispose();
  }
  if (projectChartInstance) {
    projectChartInstance.dispose();
  }

// 初始化趋势图表
  trendChartInstance = echarts.init(trendChart.value);
  trendChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['检测总量', '合格数量', '不合格数量'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '检测总量',
        type: 'bar',
        barWidth: '30%',
        data: [],
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '合格数量',
        type: 'bar',
        barWidth: '30%',
        data: [],
        itemStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '不合格数量',
        type: 'bar',
        barWidth: '30%',
        data: [],
        itemStyle: {
          color: '#EE6666'
        }
      }
    ]
  });

// 初始化项目分布图表
  projectChartInstance = echarts.init(projectChart.value);
  projectChartInstance.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '检测项目分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  });
};

const refreshData = () => {
  fetchTableData();
  ElMessage.success(' 数据已刷新');
};

const exportData = () => {
  ElMessage.success(' 导出功能开发中');
};

const handleSearchClear = () => {
  currentPage.value = 1;
};

const handleSortChange = ({prop, order}) => {
  console.log(' 排序变更:', prop, order);
};

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handlePageChange = (val) => {
  currentPage.value = val;
};

const showDetail = (row) => {
  currentDetail.value = {...row};
  detailDialogVisible.value = true;
};

const getRankTagType = (rank) => {
  if (rank === 1) return 'danger';
  if (rank === 2) return 'warning';
  if (rank === 3) return 'success';
  return '';
};

const getResultTagType = (result) => {
  switch (result) {
    case '阴性':
      return 'success';
    case '阳性':
      return 'danger';
    default:
      return 'info';
  }
};

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (trendChartInstance) {
    trendChartInstance.resize();
  }
  if (projectChartInstance) {
    projectChartInstance.resize();
  }
};

// 生命周期钩子
onMounted(() => {
  initCharts();
  fetchTableData();
  window.addEventListener('resize', handleResize);
});

// 监听数据变化
watch(allTableData, () => {
  updateTrendChart();
  updateProjectChart();
});
</script>

<style scoped>
.sample-info-query {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.header .actions {
  display: flex;
  gap: 12px;
}

.metrics-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.metric-card {
  border-radius: 8px;
  border: none;
}

.metric-content {
  display: flex;
  align-items: center;
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.metric-info {
  flex: 1;
}

.metric-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.metric-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.metric-change {
  font-size: 12px;
  color: #909399;
}

.metric-change .up {
  color: #67C23A;
}

.metric-change .down {
  color: #F56C6C;
}

.content-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 20px;
}

.chart-card, .table-card {
  border-radius: 8px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.table-card .table-actions {
  display: flex;
  gap: 12px;
}

.table-card .pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.table-card .unit {
  font-size: 12px;
  color: #909399;
  margin-left: 2px;
}

.table-card .up {
  color: #67C23A;
}

.table-card .down {
  color: #F56C6C;
}
</style>